package edu.misaka.moe.utils;

import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;



public class JdbcTemplate {
	private static Logger log=Logger.getLogger(JdbcTemplate.class);
	public static int update(String sql,Object...param) {
		int rowNum = 0;
		try {
			PreparedStatement psmt=DBConnection.getConnection().prepareStatement(sql);
			ParameterMetaData pmd=psmt.getParameterMetaData();
			if(param!=null&&param.length!=0&param.length==pmd.getParameterCount()) {
				for(int i = 0,len=param.length;i<len;i++) {
					psmt.setObject(i+1, param[i]);
				}				
			}
			rowNum=psmt.executeUpdate();
		} catch (SQLException e) {
			System.out.println(": update users by sql method error,message is "+e.getMessage());
		}finally {
			try {
				if(DBConnection.getConnection().getAutoCommit()) {
					DBConnection.closeConnection(DBConnection.getConnection());
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return rowNum;
	}
	public static <T> T query(String sql,ResultSetHandler<T> rsh,Object...param) {
		T t=null;
		PreparedStatement psmt;
		try {
			psmt = DBConnection.getConnection().prepareStatement(sql);
			ParameterMetaData pmd=psmt.getParameterMetaData();
			if(param!=null&&param.length!=0&pmd.getParameterCount()==param.length) {
				for(int i=1;i<=param.length;i++) {
					psmt.setObject(i, param[i-1]);
				}
			}
			ResultSet rs=psmt.executeQuery();
			t=rsh.handler(rs);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				if(DBConnection.getConnection().getAutoCommit()) {
					DBConnection.closeConnection(DBConnection.getConnection());
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return t;
	} 
	
	public static int queryForCount(String sql,Object...param) {
		int rowNumber=0;
		try {
			PreparedStatement psmt=DBConnection.getConnection().prepareStatement(sql);
			ParameterMetaData pmd=psmt.getParameterMetaData();
			if(param!=null&&param.length!=0&param.length==pmd.getParameterCount()) {
				for(int i = 0,len=param.length;i<len;i++) {
					psmt.setObject(i+1, param[i]);
				}				
			}
			
			ResultSet rs=psmt.executeQuery();
			if(rs.next()) {
				rowNumber=rs.getInt(1);
			}
		} catch (SQLException e) {
			log.error("queryForCount method error,this exception is:"+e.getMessage());
		} finally {
			try {
				if(DBConnection.getConnection().getAutoCommit()) {
					DBConnection.closeConnection(DBConnection.getConnection());
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return rowNumber;
	}
	
	
	
	
	
	
}
